package com.dzu.gulimall.sso.server.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author ZhaoDong
 * @date 2022/6/29 18:39
 * @description gulimall
 */
@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(String token) {
        return stringRedisTemplate.opsForValue().get(token);
    }


    @GetMapping("/login.html")
    public String toLogin(@RequestParam("redirect_url") String url, Model model, @CookieValue(value = "sso_token", required = false) String sso_token) {

        if (!StringUtils.isEmpty(sso_token)) {
            // 说明之前有人登陆过，留下了痕迹
            return "redirect:" + url + "?token=" + sso_token;

        }

        model.addAttribute("url", url);
        return "login";
    }

    @PostMapping("/doLogin")
    public String login(String username, String password, String url, HttpServletResponse response) {
        if (!StringUtils.isEmpty(username) || !StringUtils.isEmpty(password)) {

            //把登陆成功的用户存储起来
            String uuid = UUID.randomUUID().toString().replace("-", "");
            stringRedisTemplate.opsForValue().set(uuid, username);

            Cookie cookie = new Cookie("sso_token", uuid);
            response.addCookie(cookie);

            return "redirect:" + url + "?token=" + uuid;

        }

        // 登陆成功跳转、条回到之前的页面
        return "login";

    }
}
